package com.example.petstore.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.Category;
import com.example.petstore.domain.Item;
import com.example.petstore.domain.Product;
import com.example.petstore.mapper.CartItemMapper;
import com.example.petstore.mapper.CategoryMapper;
import com.example.petstore.mapper.ItemMapper;
import com.example.petstore.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
//import java.util.Map;

//import java.util.*;

@Service("itemService")
public class ItemService {
    @Autowired
    private ItemMapper itemMapper;
     @Autowired
     private CategoryMapper categoryMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductService productService;
    @Autowired
    private LineItemService lineItemService;

    public CommonResponse getItemByItemid(String itemId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("itemid", itemId);
        Item item = itemMapper.selectOne(queryWrapper);
        if(item == null){
            return CommonResponse.creatForError("出错了，请稍后再试");
        }
        return CommonResponse.creatForSuccess(item);
    }
    public List<Item> getItemsOrderedByViewsDesc() {
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Item::getViews);
        return itemMapper.selectList(queryWrapper);
    }
    public CommonResponse<HashMap<HashMap<String, Object>, Integer>> getItemsOrderedByPrice() {
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Item::getListprice);
        List<Item> itemList = itemMapper.selectList(queryWrapper);
        System.out.println("itemList"+itemList);
        return addQuantityToItems(itemList);
    }


    public CommonResponse<List<Item>> getItemList() {
        List<Item> items = itemMapper.selectList(null);
        return CommonResponse.creatForSuccess(items);
    }

    public CommonResponse addViews(String itemid) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("itemid", itemid);
        Item item = itemMapper.selectOne(queryWrapper);
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("itemid", itemid);
        updateWrapper.set("views", item.getViews() + 1);
        int result = itemMapper.update(updateWrapper);
        if(result == 1){
            return CommonResponse.creatForSuccess();
        }
        return CommonResponse.creatForError();
    }

    public CommonResponse deleteItemByItemId(String itemId) {
        System.out.println("itemId = " + itemId);
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("itemid", itemId);
        int res = itemMapper.delete(queryWrapper);
        if(res > 0) {
            return CommonResponse.creatForSuccess();
        }
        else {
            return CommonResponse.creatForError();
        }
    }
    public CommonResponse<Item> addItem(Item item) {
        int res = itemMapper.insert(item);
        if(res > 0) {
            return CommonResponse.creatForSuccess(item);
        }
        else {
            return CommonResponse.creatForError();
        }
    }
    public CommonResponse updateItemByItemId(String itemId, Item newItem) {
        UpdateWrapper<Item> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("itemid", itemId);

       int res = itemMapper.update(newItem, updateWrapper);
       if(res==1) {
           return CommonResponse.creatForSuccess();
        }
       else {
           return CommonResponse.creatForError();
       }
    }

    public CommonResponse updateIsUpByItemId(String itemId, int newIsUpValue) {
        UpdateWrapper<Item> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("itemid", itemId);
        int res = itemMapper.update(null, updateWrapper.set("isup", newIsUpValue));
        if(res > 0) {
            return CommonResponse.creatForSuccess();
        }
        else {
            return CommonResponse.creatForError();
        }
    }
    public int sumViews() {
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Item::getViews).isNotNull(Item::getViews);

        Integer sum = itemMapper.selectList(queryWrapper)
                .stream()
                .mapToInt(Item::getViews)
                .sum();

        return sum;
    }
    public CommonResponse<HashMap<HashMap<String, Object>, Integer>> addQuantityToItems(List<Item> items) {
        List<HashMap<String, Object>> itemMapList = getItemListWithProductAndCategory(items).getData();
        //System.out.println("itemMapList "+itemMapList );
        List<HashMap.Entry<String, Integer>> sortedList = lineItemService.calculateTotalQuantityAndSort();

        // 创建一个Map，存储itemid和对应的数量
        HashMap<String, Integer> salesMap = new LinkedHashMap<>();
        for (HashMap.Entry<String, Integer> entry : sortedList) {
            salesMap.put(entry.getKey(), entry.getValue());
        }
        HashMap<HashMap<String, Object>, Integer> salesitemMap = new LinkedHashMap<>();
        for (HashMap<String, Object> itemMap : itemMapList) {
            Item item = (Item)itemMap.get("item"); // 获取键名为 "item" 的值
            String itemId = item.getItemid();
            // 检查itemid是否在Map中
            if (salesMap.containsKey(itemId)) {
                salesitemMap.put(itemMap,salesMap.get(itemId));

            } else {
                // 如果不在Map中，将数量属性设置为0
                salesitemMap.put(itemMap,0);
            }
        }
        return CommonResponse.creatForSuccess(salesitemMap);
    }


    public CommonResponse<HashMap<HashMap<String, Object>, Integer>> getItemListInOrderBySales(List<String> itemIdList) {
        // 查询数据库中符合条件的商品列表
        List<Item> itemListInOrder = new ArrayList<>();
        for (String itemId : itemIdList) {
            QueryWrapper<Item> queryWrapper = new QueryWrapper<>(); // 每次循环创建新的 QueryWrapper
            queryWrapper.eq("itemid", itemId);
            Item item = itemMapper.selectOne(queryWrapper);
            itemListInOrder.add(item);
        }
        // 将不包含在 itemIdList 中的条目排在最后
        QueryWrapper<Item> queryWrapperNotIn = new QueryWrapper<>();
        queryWrapperNotIn.notIn("itemid", itemIdList);
        List<Item> itemListNotInOrder = itemMapper.selectList(queryWrapperNotIn);

        itemListInOrder.addAll(itemListNotInOrder); // 将不包含在 itemIdList 中的条目添加到结果列表的末尾
        //System.out.println("itemListInOrder"+itemListInOrder);
        return addQuantityToItems(itemListInOrder);
    }

    public CommonResponse<List<Item>> getItemListByProductId(String productId) {
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("productid", productId);

        List<Item> itemList = itemMapper.selectList(queryWrapper);

        return CommonResponse.creatForSuccess(itemList);
    }
    public CommonResponse<HashMap<HashMap<String, Object>, Integer>> getItemListByIsUp(int isUp) {
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isup", isUp);

        List<Item> itemList = itemMapper.selectList(queryWrapper);

        return addQuantityToItems(itemList);
    }
    public CommonResponse<HashMap<HashMap<String, Object>, Integer>> getItemListByKey(String keyWord) {
        System.out.println("qqqq" + keyWord);
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Product> queryWrapper2 = new QueryWrapper<>();

        queryWrapper.like("catid",keyWord.toUpperCase());
        queryWrapper2.like("name",keyWord);
        List<Category> categoryList = categoryMapper.selectList(queryWrapper);
        System.out.println(categoryList);
        List<Product> productList = productMapper.selectList(queryWrapper2);
        System.out.println(productList);
        HashMap<HashMap<String, Object>, Integer> newMap = new HashMap<>();
        if(!productList.isEmpty()){
            for (Product product :productList) {
                List<Item> itemList = getItemListByProductId(product.getProductid()).getData();
                 newMap = addQuantityToItems(itemList).getData();
//                for (Item item:itemList) {
//                    Map<String, Object> itemMap = new HashMap<>();
//                    itemMap.put("item", item);
//                    itemMap.put("product", product);
//                    itemMap.put("category", categoryService.getCategoryById(product.getCategory()));
//                    itemMapList.add(itemMap);
//                }

            }
        }
        if (!categoryList.isEmpty()) {
            for (Category category : categoryList) {
                List<Product> productList1 = productService.getProductListByCategory(category.getCatid()).getData();
                for (Product product :productList1) {
                    List<Item> itemList = getItemListByProductId(product.getProductid()).getData();
                    System.out.println("4"+itemList);
                     newMap = addQuantityToItems(itemList).getData();
//                    }

                }

            }
        }
        return CommonResponse.creatForSuccess(newMap);
    }
//    public CommonResponse getOrderListByKey(String keyWord) {
//        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like("username", keyWord).or().like("orderid", keyWord);
//        List<Item> itemList = itemMapper.selectList(queryWrapper);
//        System.out.println(itemList);
//        return CommonResponse.creatForSuccess(itemList);
//    }

    public CommonResponse<List<HashMap<String, Object>>> getItemListWithProductAndCategory(List<Item> itemList) {
       // List<Item> itemList = itemMapper.selectList(null);
        List<HashMap<String, Object>> itemMapList = new ArrayList<>();
        System.out.println("kankan "+itemList);
        for (Item item : itemList) {
            System.out.println("e");
//           System.out.println(item.getProductid());
//            todo: item可能为null??
           if(item == null){
               continue;
           }
            Product product = productService.getProductById(item.getProductid());
           // System.out.println(product);
            Category category = categoryService.getCategoryById(product.getCategory());

            HashMap<String, Object> itemMap = new LinkedHashMap<>();
            itemMap.put("item", item);
            itemMap.put("product", product);
            itemMap.put("category", category);

            itemMapList.add(itemMap);
        }

        return CommonResponse.creatForSuccess(itemMapList);
    }
}
